package com.step.ems.pages.wb

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.step.ems.api.ApiService
import com.step.ems.api.WbStatus
import com.step.ems.api.req.WbReq
import com.step.ems.api.res.WbRes
import com.step.ems.pages.common.PageViewModel
import com.step.ems.common.RefreshType
import com.step.ems.common.UiState
import com.step.ems.common.launch
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class WbPageViewModel @Inject constructor(
    private val apiService: ApiService
) : PageViewModel<WbRes>() {

    var filter by mutableStateOf("")
    var wbStatusIndex by mutableIntStateOf(0)

    init {
        getData(RefreshType.Init, 250)
    }

    fun getData(refreshType: RefreshType, delayTime: Long = 0) {
        launch(
            state = _uiState,
            delayTime = delayTime,
            onStart = {
                _uiState.value = UiState.Loading(refreshType)
            }) {
            if (refreshType != RefreshType.LoadMore) pageIndex = 1
            val req = WbReq(filter, WbStatus.entries[wbStatusIndex].value, pageIndex)
            val res = apiService.wbList(req).get()
            _data.value = when (refreshType) {
                RefreshType.LoadMore -> _data.value + res.records
                else -> res.records
            }
            pageIndex++
            _uiState.value = UiState.Success
        }
    }
}